const OSS = require('ali-oss')
import {
    stsToken
} from '@/api/oss.js'

let ossConfig = null;
// 取消上传控制项
let isCancel = false;

// 设置客户端请求访问凭证的地址 
const OssFunc = async() => {
    
    let res = await stsToken();
    ossConfig = res.data;
    
    const client = new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
        bucket: 'health-fcd',
        region: 'oss-cn-hangzhou',
        accessKeyId: ossConfig.accessKeyId,
        accessKeySecret: ossConfig.accessKeySecret,
        stsToken: ossConfig.securityToken,
        timeout: 600000,
        // HTTPS (secure: true) or HTTP (secure: false) protocol
        secure: false,
        refreshSTSTokenInterval: 3000000,
        refreshSTSToken: stsToken().then(res => {
            if (res.status === 0) {
                console.log('成功刷新oss token');
                ossConfig.accessKeyId = res.data.accessKeyId;
                ossConfig.accessKeySecret = res.data.accessKeySecret;
                ossConfig.securityToken = res.data.securityToken;
            }
        })
    });

    return client;
};

// 分片上传方法（没有设置分片相关设置，采用默认）
async function put(fileName, file) {
    try {
        let oss = await OssFunc();
        const result = await oss.multipartUpload(fileName, file, {
            'headers': {
                'Access-Control-Allow-Origin': '*',
            },
            'progress': (progress) => {
                // console.log('progress:', progress)
                if (isCancel) {
                    oss.cancel();
                    // 复位
                    isCancel = false;
                }
            }
        });
        return result;
    } catch (e) {
        console.log(e);
    }
}

// 设置取消上传标志位为true 
async function cancelUpload() {
    isCancel = true;
    return true;
}

// 获取oss文件临时路径 
async function getUrl(name) {
    try {
        let oss = await OssFunc();
        const result = await oss.signatureUrl(name);
        return result;
    } catch (e) {
        console.log(e);
    }
}

export {
    put,
    getUrl,
    cancelUpload,
}
